<div class="importDataModel" id="importDataModel">
    <div class="layui-form-item">
        <button class="layui-btn layui-btn-primary layui-btn-sm" type="button" id="downLoadTemporary">下载表模板</button>
    </div>
    <div class="layui-form-item layui-form-text">
        <button id="file-btn-upload" class="layui-btn layui-btn-sm layui-btn-normal icon-btn">
            <i class="layui-icon">&#xe681;</i>上传文件
        </button>
        <p>只能上传xls/xlsx文件</p>
    </div>
    <form class="layui-form model-form layui-row" >
        <div class="layui-inline layui-row">
            <label class="layui-form-label">数据选择</label>
            <div class="layui-input-block">
                <select name="sheetName" lay-verify="sheetName" id="sheetName-templ-box">
                </select>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary layui-btn-sm" type="button" ew-event="closePageDialog">取消</button>
            <button class="layui-btn layui-btn-sm" lay-filter="importDataSubmit" lay-submit >确定</button>
        </div>
    </form>

</div>

<script type="text/tmpl" id="sheetName-templ">
{{each sheetInfos}}
    <option value="{{$value.name}}">{{$value.name}}</option>
{{/each}}
</script>

<script>
    //获取权限方法
    var userInfo = getAuthority();
    layui.use(['layer', 'form', 'admin','upload'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var admin = layui.admin;
        var upload = layui.upload;

        var Authorization ;
        var uploadExcel = {};
        form.render('select')

        var args = admin.getLayerData("#importDataModel");

        if(userInfo){
            var access_token = localStorage.getExpire("access_token");
            var token_type = localStorage.getExpire("token_type");
            Authorization = token_type+" "+access_token;
        }

        $("#downLoadTemporary").click(function(){
            var url = macroUrl.data.download;
            downloadTemplate(url);
        });

        function downloadTemplate(url){
            var formData = new FormData();
            formData.append("column_table",args.column_table);
            formData.append("cross_table ",args.cross_table );
            formData.append("data_table  ",args.data_table  );
            formData.append("row_table ",args.row_table );
            let xhr = new XMLHttpRequest();
            xhr.open("POST", url, true); // 也可以使用POST方式，根据接口
            xhr.responseType = "blob"; // 返回类型blob，XMLHttpRequest支持二进制流类型
            xhr.setRequestHeader("Authorization", Authorization);
            xhr.onload = function() {
                if (this.status === 200) {
                    let blob = this.response; //使用response作为返回，而非responseText
                    let reader = new FileReader();
                    reader.readAsDataURL(blob); // 转换为base64，可以直接放入a标签href
                    reader.onload = function(e) {
                        // 转换完成，创建一个a标签用于下载
                        let a = document.createElement("a");
                        a.download = "模板.xlsx";
                        a.href = e.target.result;
                        a.click();
                    };
                }
            };
            xhr.send(formData);
        }

        //指定允许上传的文件类型
        upload.render({
            elem: '#file-btn-upload'
            ,url: macroUrl.data.uploadTemplate
            ,accept: 'file' //普通文件
            ,exts: 'xls|xlsx' //只允许上传压缩文件
            ,headers: {Authorization: Authorization}
            ,done: function(res){                
                if(res.message=="success"){
                    var data = res.data;
                    var str = template("sheetName-templ",data);
                    document.getElementById("sheetName-templ-box").innerHTML = str;
                    form.render('select')
                    uploadExcel = data;
                }

            }
            ,error: function(index, upload){
                console.log(index,upload)
            }
        });

        form.on('submit(importDataSubmit)', function (data) {            
            if(data.field.sheetName==null || data.field.sheetName==""){
                layer.msg('请先选择数据', {icon: 2});
                return false;
            }
            var req={
                column_table:args.column_table,
                cross_table:args.cross_table,
                data_table:args.data_table,
                row_table:args.row_table,
                fileName:uploadExcel.fileName,
                maid:args.maid,
                rcid:args.rcid,
                regioncode:args.regioncode,
                sheetName:data.field.sheetName,
                mongoId:data.mongoId //文件存入mongo中的id
            }

            axios({
                method: 'POST',
                url:macroUrl.data.analysisTemplate,
                data:$.param(req),
                headers:{
                    'Authorization':Authorization
                }
            })
                .then(function (response) {
                    if(response.data.message=="success"){
                        layer.msg(response.data.message, {icon: 1});
                        setTimeout(function () {
                            window.macroImportDataStatus = true;
                            admin.closeDialog("#importDataModel")
                        },1500);
                    }else{
                        layer.msg(response.data.message, {icon: 2});
                    }
                })
                .catch(function (error) {
                    console.log(error);
                    if(error.response.status === 401 || error.response.status === 403 || error.response.status === 406){
                        // 进行重新登陆
                        localStorage.clear();
                        top.location.href=loginPageUrl;
                    }
                });
            return false;
        });

    });
</script>

<style>
    #slideImportRegion{
        width: 184px;
        height: 20px;
        display: inline-block;
        margin-top: 20px;
    }
    #importDataModel .layui-row{
        margin-top: 10px;
    }

    #importDataModel .layui-row .layui-form-label{
        padding-left: 0;
        text-align: left;
    }

    #importDataModel .layui-row .layui-input-block{
        margin-left: 95px;
    }
    #importDataModel  .pressBox{
        display: none;
    }
    #importDataModel form{
        padding: 0;
    }
    #importDataModel .text-right{
        margin-top: 25px;
    }
    #importDataModel .subinfo{
        color: red;
        font-size: 12px;
        margin: 0;
        display: none;
    }
    .importDataModel p{
        font-size: 12px;
        color: #000000a1;
        float: left;
        margin: 14px 0 0 5px;
    }
    #file-btn-upload{
        float: left;
    }
</style>